package com.ruoyi.web.controller.system;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.DishDto;
import com.ruoyi.system.domain.vo.TodayOrderCountVO;
import com.ruoyi.system.service.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 订单Controller
 *
 * @author ruoyi
 * @date 2025-06-24
 */
@RestController
@RequestMapping("/system/orders")
public class TOrdersController extends BaseController {
    @Autowired
    private ITOrdersService tOrdersService;

    @Autowired
    private ITOrderDetailsService orderDetailsService;

    @Autowired
    private ITTakeoutLogService takeoutLogService;

    @Autowired
    private ITDishService itDishService;
    @Autowired
    private ITBillService tBillService;
    @Autowired
    private ISysUserService userService;

    /**
     * 查询订单列表
     */
    @PreAuthorize("@ss.hasPermi('system:orders:list')")
    @GetMapping("/list")
    public TableDataInfo list(TOrders tOrders) {
        startPage();
        List<TOrders> list = tOrdersService.selectTOrdersList(tOrders);
        return getDataTable(list);
    }

    /**
     * 统计今日订单
     */
    @PreAuthorize("@ss.hasPermi('system:orders:list')")
    @GetMapping("/todayOrder")
    public AjaxResult todayOrder() {
        // 获取各状态订单数，如果为null则默认为0
        Integer status1 = Optional.ofNullable(tOrdersService.countOrderStatusNum(1)).orElse(0); // 当日待接单订单
        Integer status2 = Optional.ofNullable(tOrdersService.countOrderStatusNum(2)).orElse(0); // 当日待出餐订单
        Integer status3 = Optional.ofNullable(tOrdersService.countOrderStatusNum(3)).orElse(0); // 当日已接单订单
        Integer status4 = Optional.ofNullable(tOrdersService.countOrderStatusNum(4)).orElse(0); // 当日派送中订单
        Integer status5 = Optional.ofNullable(tOrdersService.countOrderStatusNum(5)).orElse(0); // 已完成订单
        Integer status6 = Optional.ofNullable(tOrdersService.countOrderStatusNum(6)).orElse(0); // 已取消订单
        // 获取营业额，如果为null则默认为0
        BigDecimal amount = Optional.ofNullable(tOrdersService.sumOrderAmount()).orElse(BigDecimal.ZERO);
        // 计算平均单价（避免除以0的情况）
        BigDecimal average = BigDecimal.ZERO;
        if (status5 > 0) {
            average = amount.divide(new BigDecimal(status5), 2, RoundingMode.HALF_UP);
        }
        // 计算完成订单比例（避免除以0的情况）
        int totalOrders = status1 + status2 + status3 + status4 + status5;
        String formattedProportion = "0.00";
        if (totalOrders > 0) {
            double proportion = (double) status5 / totalOrders * 100;
            formattedProportion = String.format("%.2f", proportion);
        }
        // 构建返回对象
        TodayOrderCountVO todayOrderCountVO = new TodayOrderCountVO();
        todayOrderCountVO.setStatus1(status1);
        todayOrderCountVO.setStatus2(status2);
        todayOrderCountVO.setStatus3(status3);
        todayOrderCountVO.setStatus4(status4);
        todayOrderCountVO.setStatus5(status5);
        todayOrderCountVO.setStatus6(status6);
        todayOrderCountVO.setAllStatus(totalOrders);
        todayOrderCountVO.setAverage(average);
        todayOrderCountVO.setProprotion(formattedProportion);
        todayOrderCountVO.setAmount(amount);

        return AjaxResult.success(todayOrderCountVO);
    }

    /**
     * 导出订单列表
     */
    @PreAuthorize("@ss.hasPermi('system:orders:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TOrders tOrders) {
        List<TOrders> list = tOrdersService.selectTOrdersList(tOrders);
        ExcelUtil<TOrders> util = new ExcelUtil<TOrders>(TOrders.class);
        util.exportExcel(response, list, "订单数据");
    }

    /**
     * wx小程序获取订单详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        // 根据id查询订单
        TOrders orders = tOrdersService.selectTOrdersById(id);
        // 根据id查询商品详情列表
        List<TOrderDetails> list = orderDetailsService.selectTOrderDetailsByOrdeId(id);
        orders.setDetailsList(list);
        // 根据订单id查询订单日志列表
        List<TTakeoutLog> takeoutLogsList = takeoutLogService.selecttakeoutLogByOrdeId(id);
        orders.setTakeoutLogList(takeoutLogsList);

        return success(orders);
    }

    /**
     * 小程序查询本用户订单列表
     */
    @GetMapping("/ordersListByUserId/{status}")
    public AjaxResult ordersListByUserId(@PathVariable("status") Long status) {
        //如果订单状态是100是查得全部订单列表
        if (100 == status) {
            status = null;
        }
        Long userId = SecurityUtils.getUserId();
        List<TOrders> list = tOrdersService.ordersListByUserId(userId, status);

        for (int i = 0; i < list.size(); i++) {
            TOrders tOrders = list.get(i);
            Long id = tOrders.getId();

            List<TOrderDetails> detailsList = orderDetailsService.selectTOrderDetailsByOrdeId(id);
            tOrders.setDetailsList(detailsList);
        }

        return AjaxResult.success(list);
    }

    /**
     * 新增订单
     */
    @PreAuthorize("@ss.hasPermi('system:orders:add')")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TOrders tOrders) {
        int i = tOrdersService.insertTOrders(tOrders);
        // 加一条日志跟踪
        TTakeoutLog tTakeoutLog = new TTakeoutLog();
        tTakeoutLog.setUserId(SecurityUtils.getUserId());
        tTakeoutLog.setNickname(SecurityUtils.getUsername());
        tTakeoutLog.setLogTime(new Date());
        tTakeoutLog.setDescription("下单");
        tTakeoutLog.setOrderId(tOrders.getId());
        takeoutLogService.insertTTakeoutLog(tTakeoutLog);
        return toAjax(i);
    }

    /**
     * 小程序用户新增订单
     */
//    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping("/wxUserAddOrder")
    @Transactional(rollbackFor = Exception.class)//事务（代码报错，回滚之前执行的sql）
    public AjaxResult addOrder(@RequestBody List<DishDto> dishDtoList) {
        BigDecimal totalAmount = new BigDecimal(0);//商品总价（不含配送费和打包）
        for (DishDto dishDto : dishDtoList) {
            TDish dish = itDishService.selectTDishById(dishDto.getId());
            BigDecimal sum = dish.getPrice().multiply(new BigDecimal(dishDto.getCount())); // 计算订单商品的个数*价格得到总数，
            totalAmount = totalAmount.add(sum);//然后就直接加到总价上
        }
        // 插一条订单
        TOrders orders = new TOrders();
        orders.setOrderStatus(0L);// 设置订单为待支付
        orders.setOrderNo(System.currentTimeMillis() + "");
        orders.setPackAmount(new BigDecimal(1)); // 打包费
        orders.setFreightAmount(new BigDecimal(2)); // 配送
        orders.setTotalAmount(totalAmount);//商品总费用（不含配送费和打包）
        orders.setPaymentAmount(totalAmount.add(orders.getPackAmount()).add(orders.getFreightAmount()));//总计
        orders.setUserId(SecurityUtils.getUserId());// 谁的订单
        orders.setReceiverName(SecurityUtils.getLoginUser().getUser().getNickName());
        orders.setReceiverPhone(SecurityUtils.getLoginUser().getUser().getPhonenumber());
        orders.setReceiverAddress(SecurityUtils.getLoginUser().getUser().getAddress());
        orders.setOrderStatus(0L);
        orders.setDeliveryStatus("1");
        orders.setTablewareStatus(1L);
        orders.setUpdateTime(new Date());
        // 设置预计送达时间为当前时间 + 40分钟
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 40); // 当前时间 + 40分钟
        orders.setEstimatedDeliveryTime(calendar.getTime());  //预计送达时间
        tOrdersService.insertTOrders(orders);

        // 订单跟踪
        // 加一条日志跟踪
        TTakeoutLog tTakeoutLog = new TTakeoutLog();
        tTakeoutLog.setUserId(SecurityUtils.getUserId());
        tTakeoutLog.setNickname(SecurityUtils.getLoginUser().getUser().getNickName());
        tTakeoutLog.setLogTime(new Date());
        tTakeoutLog.setDescription("待付款");
        tTakeoutLog.setOrderId(orders.getId());
        takeoutLogService.insertTTakeoutLog(tTakeoutLog);

        // 有了订单之后再加n条订单详情
        for (DishDto dishDto : dishDtoList) {
            TDish dish = itDishService.selectTDishById(dishDto.getId());
            // 一条一条循环插入
            TOrderDetails orderDetails = new TOrderDetails();
            orderDetails.setOrderId(orders.getId());// 设置这个详情是哪一个订单的
            orderDetails.setDishId(Long.valueOf(dish.getId()));
            orderDetails.setDishName(dish.getName());
            orderDetails.setDishImage(dish.getImage());
            orderDetails.setDishPrice(dish.getPrice());
            orderDetails.setQuantity(dishDto.getCount());
            orderDetails.setTotalPrice(dish.getPrice().multiply(new BigDecimal(dishDto.getCount())));  //括号里把int转为BigDecimal类型
            orderDetails.setRefundStatus(3l);
            orderDetailsService.insertTOrderDetails(orderDetails);
        }
        return AjaxResult.success(orders.getId());
    }

    /**
     * wx小程序用户提交订单（填写支付信息）
     */
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping("/wxUserEditOrder")
    @Transactional(rollbackFor = Exception.class) // 事务（代码报错，回滚之前执行的SQL）
    public AjaxResult wxUserEditOrder(@RequestBody TOrders tOrders) {
        // 1. 检查用户余额是否足够
        SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
        if (sysUser.getBalance().compareTo(tOrders.getPaymentAmount()) < 0) {
            return AjaxResult.error("钱包余额不足"); // 余额不足时直接返回错误
        }

        // 1. 更新订单状态
        tOrders.setOrderStatus(1L); // 订单状态（假设1表示"待接单"）
        tOrders.setPaymentTime(new Date()); // 支付时间
        tOrders.setUpdateTime(new Date()); // 更新时间
        if ("1".equals(tOrders.getDeliveryStatus())){
            // 设置预计送达时间为支付时间后加40分钟
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(tOrders.getPaymentTime());
            calendar.add(Calendar.MINUTE, 40);
            tOrders.setEstimatedDeliveryTime(calendar.getTime());  //预计送达时间
        }

        tOrdersService.updateTOrders(tOrders);

        // 2. 记录订单日志（待接单）
        TTakeoutLog tTakeoutLog = new TTakeoutLog();
        tTakeoutLog.setUserId(SecurityUtils.getUserId());
        tTakeoutLog.setNickname(SecurityUtils.getLoginUser().getUser().getNickName());
        tTakeoutLog.setLogTime(new Date());
        tTakeoutLog.setDescription("已下单");
        tTakeoutLog.setOrderId(tOrders.getId());
        takeoutLogService.insertTTakeoutLog(tTakeoutLog);


        // 4. 扣除用户余额（事务内操作）
        Long userId = tOrders.getUserId();
        BigDecimal amount = tOrders.getPaymentAmount().multiply(new BigDecimal(-1)); // 负数表示扣款
        userService.updatieUserBalance(userId, amount);

        // 5. 记录支付账单
        TBill bill = new TBill();
        bill.setUserId(SecurityUtils.getUserId());
        bill.setPayTime(new Date());
        bill.setBillType(1L); // 1表示"支付"
        bill.setPaymentMethod(1L); // 1表示"钱包"
        bill.setDescription("支付账单");
        bill.setCreateTime(new Date());
        bill.setAmount(amount); // 金额为正数（账单记录通常用正数）
        tBillService.insertTBill(bill);

        return AjaxResult.success();
    }

    /**
     * wx小程序取消订单
     */
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @Transactional(rollbackFor = Exception.class) // 事务（代码报错，回滚之前执行的SQL）
    @GetMapping(value = "/wxUserCancelOrder/{id}")
    public AjaxResult wxUserCancelOrder(@PathVariable("id") Long id) {
        TOrders orders = new TOrders();
        orders.setId(id);
        orders.setOrderStatus(6L); // 订单状态（6表示"已取消"）
        orders.setCancelTime(new Date()); // 取消时间
        orders.setUpdateTime(new Date()); // 更新时间
        tOrdersService.updateTOrders(orders);

        // 2. 记录订单日志
        TTakeoutLog tTakeoutLog = new TTakeoutLog();
        tTakeoutLog.setUserId(SecurityUtils.getUserId());
        tTakeoutLog.setNickname(SecurityUtils.getLoginUser().getUser().getNickName());
        tTakeoutLog.setLogTime(new Date());
        tTakeoutLog.setDescription("已取消");
        tTakeoutLog.setOrderId(orders.getId());
        takeoutLogService.insertTTakeoutLog(tTakeoutLog);

        return AjaxResult.success();
    }


    /**
     * 修改订单
     */
    @PreAuthorize("@ss.hasPermi('system:orders:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TOrders tOrders) {
        return toAjax(tOrdersService.updateTOrders(tOrders));
    }

    /**
     * 工作人员接受订单（食堂接单）
     */
//    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @GetMapping("/receiveOrder/{id}")
    @Transactional(rollbackFor = Exception.class) // 事务（代码报错，回滚之前执行的SQL）
    public AjaxResult receiveOrder(@PathVariable("id")Long id) {
        // 1. 更新订单状态
        TOrders tOrders = new TOrders();
        tOrders.setId(id);
        tOrders.setOrderStatus(2L); // 订单状态（表示"待出餐"）
        tOrders.setUpdateTime(new Date()); // 更新时间
        tOrdersService.updateTOrders(tOrders);

        // 2. 记录订单日志（待出餐）
        TTakeoutLog tTakeoutLog = new TTakeoutLog();
        tTakeoutLog.setUserId(SecurityUtils.getUserId());
        tTakeoutLog.setNickname(SecurityUtils.getLoginUser().getUser().getNickName());
        tTakeoutLog.setLogTime(new Date());
        tTakeoutLog.setDescription("待出餐");
        tTakeoutLog.setOrderId(tOrders.getId());
        takeoutLogService.insertTTakeoutLog(tTakeoutLog);

        return AjaxResult.success();
    }
    /**
     * 工作人员拒绝订单（拒单）
     */
//    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @GetMapping("/refuseOrder/{id}")
    @Transactional(rollbackFor = Exception.class) // 事务（代码报错，回滚之前执行的SQL）
    public AjaxResult refuseOrder(@PathVariable("id")Long id) {
        // 1. 更新订单状态
        TOrders tOrders = new TOrders();
        tOrders.setId(id);
        tOrders.setOrderStatus(6L); // 订单状态（取消"）
        tOrders.setUpdateTime(new Date()); // 更新时间
        tOrdersService.updateTOrders(tOrders);

        // 2. 记录订单日志
        TTakeoutLog tTakeoutLog = new TTakeoutLog();
        tTakeoutLog.setUserId(SecurityUtils.getUserId());
        tTakeoutLog.setNickname(SecurityUtils.getLoginUser().getUser().getNickName());
        tTakeoutLog.setLogTime(new Date());
        tTakeoutLog.setDescription("已拒单");
        tTakeoutLog.setOrderId(tOrders.getId());
        takeoutLogService.insertTTakeoutLog(tTakeoutLog);

        // 查询订单支付了多少钱
        TOrders orders = tOrdersService.selectTOrdersById(id);

        // 4. 退回用户余额（事务内操作）
        Long userId = orders.getUserId();
        BigDecimal amount = orders.getTotalAmount(); // 负数表示扣款
        userService.updatieUserBalance(userId, amount);

        // 5. 记录支付账单
        TBill bill = new TBill();
        bill.setUserId(SecurityUtils.getUserId());
        bill.setPayTime(new Date());
        bill.setBillType(2L); // 1表示"收入"
        bill.setPaymentMethod(1L); // 1表示"钱包"
        bill.setDescription("拒单退款");
        bill.setCreateTime(new Date());
        bill.setAmount(amount); // 金额为正数（账单记录通常用正数）
        tBillService.insertTBill(bill);
        return AjaxResult.success();
    }
    /**
     * 工作人员出餐订单（出餐确认）
     */
//    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @GetMapping("/dispatchOrder/{id}")
    @Transactional(rollbackFor = Exception.class) // 事务（代码报错，回滚之前执行的SQL）
    public AjaxResult dispatchOrder(@PathVariable("id")Long id) {
        // 1. 更新订单状态
        TOrders tOrders = new TOrders();
        tOrders.setId(id);
        tOrders.setOrderStatus(3L); // 订单状态（表示"待派送"）
        tOrders.setUpdateTime(new Date()); // 更新时间
        tOrdersService.updateTOrders(tOrders);

        // 2. 记录订单日志
        TTakeoutLog tTakeoutLog = new TTakeoutLog();
        tTakeoutLog.setUserId(SecurityUtils.getUserId());
        tTakeoutLog.setNickname(SecurityUtils.getLoginUser().getUser().getNickName());
        tTakeoutLog.setLogTime(new Date());
        tTakeoutLog.setDescription("已出餐，待取货");
        tTakeoutLog.setOrderId(tOrders.getId());
        takeoutLogService.insertTTakeoutLog(tTakeoutLog);

        return AjaxResult.success();
    }
    /**
     * 工作人员取单（取货确认）
     */
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @GetMapping("/pickOrder/{id}")
    @Transactional(rollbackFor = Exception.class) // 事务（代码报错，回滚之前执行的SQL）
    public AjaxResult pickUpOrder(@PathVariable("id")Long id) {
        // 1. 更新订单状态
        TOrders tOrders = new TOrders();
        tOrders.setId(id);
        tOrders.setOrderStatus(4L); // 订单状态（表示"派送中"）
        tOrders.setDeliveryTime(new Date());  //发货时间
        tOrders.setDeliveryId(SecurityUtils.getLoginUser().getUser().getUserId()); //配送人id
        tOrders.setDeliveryName(SecurityUtils.getLoginUser().getUser().getUserName());  //配送人
        tOrders.setDeliveryPhone(SecurityUtils.getLoginUser().getUser().getPhonenumber());  //psr电话
        tOrders.setUpdateTime(new Date()); // 更新时间
        tOrdersService.updateTOrders(tOrders);

        // 2. 记录订单日志
        TTakeoutLog tTakeoutLog = new TTakeoutLog();
        tTakeoutLog.setUserId(SecurityUtils.getUserId());
        tTakeoutLog.setNickname(SecurityUtils.getLoginUser().getUser().getNickName());
        tTakeoutLog.setLogTime(new Date());
        tTakeoutLog.setDescription("已取货，正在赶往收货地址");
        tTakeoutLog.setOrderId(tOrders.getId());
        takeoutLogService.insertTTakeoutLog(tTakeoutLog);

        return AjaxResult.success();
    }
    /**
     * 工作人员完成订单（配送完成）
     */
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @GetMapping("/finishOrder/{id}")
    @Transactional(rollbackFor = Exception.class) // 事务（代码报错，回滚之前执行的SQL）
    public AjaxResult finishOrder(@PathVariable("id")Long id) {
        // 1. 更新订单状态
        TOrders tOrders = new TOrders();
        tOrders.setId(id);
        tOrders.setOrderStatus(5L); // 订单状态（表示"已完成"）
        tOrders.setDeliveryTime(new Date());  //发货时间
        tOrders.setDeliveryId(SecurityUtils.getLoginUser().getUser().getUserId()); //配送人id
        tOrders.setDeliveryName(SecurityUtils.getLoginUser().getUser().getUserName());  //配送人
        tOrders.setDeliveryPhone(SecurityUtils.getLoginUser().getUser().getPhonenumber());  //psr电话
        tOrders.setReceiveTime(new Date());  //收货时间
        tOrders.setUpdateTime(new Date()); // 更新时间
        tOrdersService.updateTOrders(tOrders);

        // 2. 记录订单日志
        TTakeoutLog tTakeoutLog = new TTakeoutLog();
        tTakeoutLog.setUserId(SecurityUtils.getUserId());
        tTakeoutLog.setNickname(SecurityUtils.getLoginUser().getUser().getNickName());
        tTakeoutLog.setLogTime(new Date());
        tTakeoutLog.setDescription("订单已完成");
        tTakeoutLog.setOrderId(tOrders.getId());
        takeoutLogService.insertTTakeoutLog(tTakeoutLog);

        return AjaxResult.success();
    }
    /**
     * 工作人员转接配送订单（配送转接）
     */
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @GetMapping("/transferOrder/{id}")
    @Transactional(rollbackFor = Exception.class) // 事务（代码报错，回滚之前执行的SQL）
    public AjaxResult transferOrder(@PathVariable("id")Long id) {
        // 1. 更新订单状态
        TOrders tOrders = new TOrders();
        tOrders.setId(id);
        tOrders.setOrderStatus(3L); // 订单状态（表示"已完成"）
        tOrders.setDeliveryTime(new Date());  //发货时间
        tOrders.setDeliveryId(SecurityUtils.getLoginUser().getUser().getUserId()); //配送人id
        tOrders.setDeliveryName(SecurityUtils.getLoginUser().getUser().getUserName());  //配送人
        tOrders.setDeliveryPhone(SecurityUtils.getLoginUser().getUser().getPhonenumber());  //psr电话
//        tOrders.setReceiveTime(new Date());  //收货时间
        tOrders.setUpdateTime(new Date()); // 更新时间
        tOrdersService.updateTOrders(tOrders);

        // 2. 记录订单日志
        TTakeoutLog tTakeoutLog = new TTakeoutLog();
        tTakeoutLog.setUserId(SecurityUtils.getUserId());
        tTakeoutLog.setNickname(SecurityUtils.getLoginUser().getUser().getNickName());
        tTakeoutLog.setLogTime(new Date());
        tTakeoutLog.setDescription("转单，待取货");
        tTakeoutLog.setOrderId(tOrders.getId());
        takeoutLogService.insertTTakeoutLog(tTakeoutLog);

        return AjaxResult.success();
    }

    /**
     * 小程序（食堂出餐）查询新订单列表
     */
    @GetMapping("/newList")
    public AjaxResult newList(TOrders tOrders) {
        List<TOrders> list = tOrdersService.selectPendingList(tOrders);

        for (int i = 0; i < list.size(); i++) {
            TOrders orders = list.get(i);
            Long id = orders.getId();
            List<TOrderDetails> detailsList = orderDetailsService.selectTOrderDetailsByOrdeId(id);
            orders.setDetailsList(detailsList);
        }
        return  AjaxResult.success(list);
    }

    /**
     * 小程序（食堂出餐）查询制作出餐中订单列表
     */
    @GetMapping("/orderReady")
    public AjaxResult orderReady(TOrders tOrders) {
        List<TOrders> list = tOrdersService.selectOrderReady(tOrders);

//        for (int i = 0; i < list.size(); i++) {
//            TOrders orders = list.get(i);
//            Long id = orders.getId();
//            List<TOrderDetails> detailsList = orderDetailsService.selectTOrderDetailsByOrdeId(id);
//            orders.setDetailsList(detailsList);
//        }
        return  AjaxResult.success(list);
    }

    /**
     * 微信小程序(配送员)查询可接单订单列表
     */
    @GetMapping("/deliveryList")
    public AjaxResult deliveryList() {
        List<TOrders> list = tOrdersService.selectDeliveryList();
        return AjaxResult.success(list);
    }
    /**
     * 微信小程序(配送员)查询已经接单订单列表
     */
    @GetMapping("/receivedList")
    public AjaxResult receivedList() {
        Long userId = SecurityUtils.getUserId();
        List<TOrders> list = tOrdersService.selectReceivedList(userId);
        return AjaxResult.success(list);
    }

    /**
     * 配送人员抢单订单（配送人接单确认）
     */
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @GetMapping("/acceptOrder/{id}")
    @Transactional(rollbackFor = Exception.class) // 事务（代码报错，回滚之前执行的SQL）
    public AjaxResult acceptOrder(@PathVariable("id")Long id) {
        // 1. 更新订单状态
        TOrders tOrders = new TOrders();
        tOrders.setId(id);
        tOrders.setDeliveryId(SecurityUtils.getUserId()); //配送人id
        tOrders.setDeliveryName(SecurityUtils.getLoginUser().getUser().getUserName());  //配送人
        tOrders.setDeliveryPhone(SecurityUtils.getLoginUser().getUser().getPhonenumber());  //psr电话
        tOrders.setOrderStatus(3L); // 订单状态（表示"待派送"）
        tOrders.setUpdateTime(new Date()); // 更新时间
        tOrdersService.updateTOrders(tOrders);

        // 2. 记录订单日志
        TTakeoutLog tTakeoutLog = new TTakeoutLog();
        tTakeoutLog.setUserId(SecurityUtils.getUserId());
        tTakeoutLog.setNickname(SecurityUtils.getLoginUser().getUser().getNickName());
        tTakeoutLog.setLogTime(new Date());
        tTakeoutLog.setDescription("骑手已接单，待取货");
        tTakeoutLog.setOrderId(tOrders.getId());
        takeoutLogService.insertTTakeoutLog(tTakeoutLog);

        return AjaxResult.success();
    }

    /**
     * 配送员取单（取货确认）
     */
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @GetMapping("/pickOrderByDelivery/{id}")
    @Transactional(rollbackFor = Exception.class) // 事务（代码报错，回滚之前执行的SQL）
    public AjaxResult pickOrder(@PathVariable("id")Long id) {
        // 1. 更新订单状态
        TOrders tOrders = new TOrders();
        tOrders.setId(id);
        tOrders.setOrderStatus(4L); // 订单状态（表示"派送中"）
        tOrders.setDeliveryTime(new Date());  //发货时间
        tOrders.setDeliveryId(SecurityUtils.getLoginUser().getUser().getUserId()); //配送人id
        tOrders.setDeliveryName(SecurityUtils.getLoginUser().getUser().getUserName());  //配送人
        tOrders.setDeliveryPhone(SecurityUtils.getLoginUser().getUser().getPhonenumber());  //psr电话
        tOrders.setUpdateTime(new Date()); // 更新时间
        tOrdersService.updateOrders(tOrders);

        // 2. 记录订单日志
        TTakeoutLog tTakeoutLog = new TTakeoutLog();
        tTakeoutLog.setUserId(SecurityUtils.getUserId());
        tTakeoutLog.setNickname(SecurityUtils.getLoginUser().getUser().getNickName());
        tTakeoutLog.setLogTime(new Date());
        tTakeoutLog.setDescription("已取货，正在赶往收货地址");
        tTakeoutLog.setOrderId(tOrders.getId());
        takeoutLogService.insertTTakeoutLog(tTakeoutLog);

        return AjaxResult.success();
    }

    /**
     * 删除订单
     */
    @PreAuthorize("@ss.hasPermi('system:orders:remove')")
    @Log(title = "订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tOrdersService.deleteTOrdersByIds(ids));
    }


}
